package com.hardware.protocol.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Describe
 * @Author hy
 * @Date 18:15 2023/8/3
 * @version 1.0
 **/
@Component
public class MqttReciever {

    private static final Logger log = LoggerFactory.getLogger(MqttReciever.class);

    private static int QoS = 1;
    public static MqttClient mqttClient = null;
    private static MemoryPersistence memoryPersistence = null;
    private static MqttConnectOptions mqttConnectOptions = null;

    @Resource
    private MqttRecieveCallback mqttRecieveCallback;

    @Value("${mqtt.host}")
    private String mqtt_host = "tcp://127.0.0.1:1883";

    @Value("${mqtt.receiverClientId}")
    private String mqtt_receive_clientId;

    @Value("${mqtt.topic}")
    private String mqtt_topic;

    @Value("${mqtt.username}")
    private String mqtt_username;

    @Value("${mqtt.password}")
    private String mqtt_password;

    @PostConstruct
    public void init() {

        memoryPersistence = new MemoryPersistence();
        try {
            mqttClient = new MqttClient(mqtt_host, mqtt_receive_clientId, memoryPersistence);
        } catch (MqttException e) {
            log.error("mqttClient {}", e.getMessage());
        }
        mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setAutomaticReconnect(true);
        //超时时间 60秒
        mqttConnectOptions.setConnectionTimeout(60);
        //心跳时间 超时断开连接
        mqttConnectOptions.setKeepAliveInterval(30);
        mqttConnectOptions.setUserName(mqtt_username);
        mqttConnectOptions.setPassword(mqtt_password.toCharArray());
        if (null != mqttClient && !mqttClient.isConnected()) {
            try {
                mqttClient.setCallback(mqttRecieveCallback);
                mqttClient.connect(mqttConnectOptions);
                mqttClient.subscribe(mqtt_topic, QoS);
            } catch (MqttException e) {
                log.error("mqttClient {}", e.getMessage());
            }
        }
    }
}
